<template>
    <view class="container">
        <view class="header" :style="{ backgroundImage: 'url(' + bgUser + ')' }">
            <!--自定义头部状态栏-->
            <!-- #ifdef APP-PLUS -->
            <view class="status_bar"><view class="top_view"></view></view>
            <!-- #endif -->
            <view class="top"><image @click="handleClickMsg" src="../../static/img/msg.png" mode="widthFix"></image></view>
            <view class="user">
                <view class="u-flex">
                    <image class="avatar" :src="my.logo != null ? baseUrl + my.logo : defaultLogo" mode="widthFix"></image>
                    <view class="name" @click="profile">
                        <text>{{ userName }}</text>
                        <image v-if="userInfo.vipLevel > 0" class="vip" src="../../static/img/vip.png"></image>
                    </view>
                </view>
                <image @click="toLogin" class="qhsf" mode="widthFix" :src="qhsf"></image>
            </view>
            <view class="total">
                <view v-for="(item, index) in menu" :key="index" @click="handleClickMemu(item.id)">
                    <text>{{ item.num || 0 }}</text>
                    {{ item.name }}
                </view>
            </view>
        </view>

        <view class="my-home">
            <view class="star u-flex u-row-between">
                <view>
                    <text>【我的星级】</text>
                    <u-rate v-model="value" :count="count" :active-color="activeColor" :inaction-color="inactiveColor" :disabled="disabled"></u-rate>
                </view>
                <block v-if="my">
                    <navigator v-if="userInfo.vipLevel === 0" url="/pages/user/openMembership" style="color: #603e1c">
                        <image class="up-vip" src="../../static/img/up_vip.png"></image>
                        开通会员
                    </navigator>
                    <navigator v-if="userInfo.vipLevel === 1" url="/pages/user/openMembership" style="color: #603e1c">
                        <image class="up-vip" src="../../static/img/up_vip.png"></image>
                        升级会员
                    </navigator>
                    <navigator v-if="userInfo.vipLevel === 2" url="/pages/user/openMembership" style="color: #603e1c">
                        <image class="up-vip" src="../../static/img/up_vip.png"></image>
                        高级VIP
                    </navigator>
                </block>
                <block v-else>
                    <navigator url="/pages/login/login" style="color: #603e1c">
                        <image class="up-vip" src="../../static/img/up_vip.png"></image>
                        开通会员
                    </navigator>
                </block>
            </view>
            <view class="title u-flex u-row-between u-border-bottom">
                <text>我的主页</text>
                <block v-if="statusTitle == '未完善'">
                    <navigator v-if="userInfo.identityType == 1" url="../login/improveInformation">
                        {{ statusTitle }}
                        <image class="more" src="../../static/img/more.png"></image>
                    </navigator>
                    <navigator v-else url="../login/personInformation">
                        {{ statusTitle }}
                        <image class="more" src="../../static/img/more.png"></image>
                    </navigator>
                </block>

                <block v-else>
                    <navigator v-if="userInfo.identityType == 1" url="../user/myCompanyPage">
                        {{ statusTitle }}
                        <image class="more" src="../../static/img/more.png"></image>
                    </navigator>
                    <navigator v-else url="../user/myHomePage">
                        {{ statusTitle }}
                        <image class="more" src="../../static/img/more.png"></image>
                    </navigator>
                </block>
            </view>
            <view class="add u-flex u-col-center u-row-between">
                <view class="u-flex u-col-center">
                    <view class="f-logo"><image src="../../static/img/fb_logo.png" mode="aspectFill"></image></view>
                    <view>
                        <view style="padding-bottom: 10rpx; font-size: 26rpx; color: #888d99">发布需求</view>
                        <view style="font-size: 32rpx; font-weight: 700">即时得到响应</view>
                    </view>
                </view>
                <view class="btn u-m-r-22" @click="handleClickRelease">立即发布</view>
            </view>
        </view>

        <!--金刚区-->
        <view class="menus">
            <view class="title u-border-bottom"><text>常用功能</text></view>
            <m-grid :datas="grid" @click="handleClickGrid" showBorder="false" columnNum="4" show-border="false"></m-grid>
        </view>
        <!--金刚区-->
        <!-- 客服类型选择 -->
        <u-modal v-model="modalShow" title="客服类型选择" :show-cancel-button="true" :mask-close-able="true" @confirm="matchCustomerServicerByType">
            <view class="slot-content">
                <u-radio-group v-model="csTypeId">
                    <u-radio v-for="(item, index) in customerServiceType" :key="index" :name="item.id">{{ item.label }}</u-radio>
                </u-radio-group>
            </view>
        </u-modal>
        <u-modal v-model="hbModalShow" title="发红包" :show-cancel-button="true" :mask-close-able="true" @confirm="handleClickHb">
            <view>
                <u-radio-group v-model="hbTypeId">
                    <text class="slot-content-select">范围</text>
                    <u-radio :name="1">范围</u-radio>
                    <u-radio :name="2">同城</u-radio>
                    <u-radio :name="3">全网</u-radio>
                </u-radio-group>
                <view class="slot-content-input">
                    <text>金额</text>
                    <m-input placeholder="请输入金额" v-model="hbInputValue" />
                </view>
                <view class="slot-content-input">
                    <text>个数</text>
                    <m-input placeholder="请输入个数" v-model="hbCountValue" />
                </view>
                <view class="slot-content-input" @click="$refs.triTree._show()" v-if="hbTypeId == 1">
                    <text>领域</text>
                    <m-input placeholder="请选择领域" v-model="hbLyValue" />
                </view>
                <view class="slot-content-input" @click="handleShowSelect" v-if="hbTypeId == 1">
                    <text>地域</text>
                    <m-input placeholder="请选择地域" v-model="hbDyValue" />
                </view>
            </view>
            <TriTree ref="triTree" :range="fetchDict" @confirm="handleTreeChange" clear v-if="fetchDict.length !== 0"></TriTree>
        </u-modal>
        <u-toast ref="uToast" />
        <Select v-model="isSelectShow" @city-change="handleCityChange"></Select>
    </view>
</template>
<script>
import mGrid from '@/components/m-grid/m-grid.vue';
import utils from '@/common/utils.js';
import Select from '@/components/u-city-select.vue';

export default {
    components: {
        mGrid,
        Select
    },
    data() {
        return {
            hbLyValue: '',
            fetchDict: [],
            hbDyValue: '',
            isSelectShow: false,
            selectValue: {},
            modalShow: false, // 客服类型选择
            hbModalShow: false, //红包弹框
            my: '',
            profileStatus: 0,
            statusTitle: '主页设置',
            userInfo: {},
            userName: '登录/注册',
            activeColor: '#FF9900',
            inactiveColor: '#FFE2CF',
            disabled: true,
            count: 5,
            customIcon: false,
            plain: false,
            value: 4,
            baseUrl: this.$mConfig.baseUrl,
            bgUser: this.$mAssetsPath.bgUser,
            qhsf: this.$mAssetsPath.qhsf,
            logoMask: this.$mAssetsPath.logoMask,
            defaultLogo: this.$mAssetsPath.defaultLogo,
            csTypeId: '',
            hbTypeId: 2, // 红包范围类型
            hbInputValue: '', //红包额度
            hbCountValue: '', //红包个数
            customerServiceType: [],
            menu: [
                {
                    id: 1,
                    name: '我的收藏',
                    num: 0,
                    url: this.$mRoutesConfig.collection
                },
                {
                    id: 2,
                    name: '我的关注',
                    num: 0,
                    url: this.$mRoutesConfig.follow
                },
                {
                    id: 3,
                    name: '我的足迹',
                    num: 0,
                    url: this.$mRoutesConfig.footprint
                },
                {
                    id: 4,
                    name: '我的特权',
                    num: 0,
                    url: this.$mRoutesConfig.help
                }
            ],
            grid: [
                {
                    id: 1,
                    icon: this.$mAssetsPath.fp,
                    name: '发票',
                    url: this.$mRoutesConfig.invoice
                },
                {
                    id: 2,
                    icon: this.$mAssetsPath.lxkf,
                    name: '联系客服',
                    url: this.$mRoutesConfig.login
                },
                {
                    id: 3,
                    icon: this.$mAssetsPath.yjfk,
                    name: '意见反馈',
                    url: this.$mRoutesConfig.feedback
                },
                {
                    id: 4,
                    icon: this.$mAssetsPath.bz,
                    name: '帮助',
                    url: this.$mRoutesConfig.help
                },
                {
                    id: 5,
                    icon: this.$mAssetsPath.hzhb,
                    name: '合作伙伴',
                    url: this.$mRoutesConfig.partners
                },
                {
                    id: 6,
                    icon: this.$mAssetsPath.wdzh,
                    name: '我的账户',
                    url: this.$mRoutesConfig.account
                },
                {
                    id: 7,
                    icon: this.$mAssetsPath.wdtk,
                    name: '我的退款',
                    url: this.$mRoutesConfig.refund
                },
                {
                    id: 8,
                    icon: this.$mAssetsPath.wdxm,
                    name: '我的项目',
                    url: this.$mRoutesConfig.project
                },
                {
                    id: 9,
                    icon: this.$mAssetsPath.wdsz,
                    name: '设置',
                    url: this.$mRoutesConfig.setting
                },
                {
                    id: 10,
                    icon: this.$mAssetsPath.sqgl,
                    name: '授权管理',
                    url: this.$mRoutesConfig.auth
                },
                {
                    id: 11,
                    icon: this.$mAssetsPath.fbfq,
                    name: '发布发起',
                    url: this.$mRoutesConfig.mypost
                },
                {
                    id: 12,
                    icon: this.$mAssetsPath.bz,
                    name: '关于我们',
                    url: this.$mRoutesConfig.about
                },
                {
                    id: 13,
                    icon: this.$mAssetsPath.gcbx,
                    name: '工程保险',
                    url: this.$mRoutesConfig.login
                },
				// {
				// 	id: 14,
				// 	icon: this.$mAssetsPath.kcgl,
				// 	name: '课程管理',
				// 	url: this.$mRoutesConfig.myClassroom
				// }
                // {
                //     id: 14,
                //     icon: this.$mAssetsPath.hb,
                //     name: '红包',
                //     url: this.$mRoutesConfig.login
                // }
            ]
        };
    },
    onLoad() {
	},
    onShow() {
        this.dictionaryFetchDict();
			this.findUserInfoOne();

        if (uni.getStorageSync('userInfo') != '') {
            let userInfo = this.$store.state.userInfo;
            this.userInfo = userInfo;
            if (userInfo.name) {
                this.userName = userInfo.name;
            }
            this.getfetchUserReviewed();
            this.getMyIndex();
            console.log('userInfo', userInfo);
        }else{
			this.userName = '登录/注册'
		}

        // #ifdef APP-PLUS
        uni.showTabBar();
        this.$tabbarView.$watch();
        // #endif
    },
    onHide() {
        // #ifdef APP-PLUS
        this.$tabbarView.$watch();
        // #endif
    },
    onPullDownRefresh() {},
    onReachBottom() {},
    //导航按钮
    onNavigationBarButtonTap(obj) {
        this.msg();
    },
    watch: {
        value(n) {
            // console.log(n);
        },
        hbTypeId(){
           this.dictionaryFetchDict();
        }
    },
    computed: {
        activeIcon() {
            let icon = this.customIcon ? 'heart' : 'star';
            return this.plain ? icon : icon + '-fill';
        },
        inactiveIcon() {
            let icon = this.customIcon ? 'heart' : 'star';
            return this.plain ? icon : icon + '-fill';
        }
    },
    methods: {
		async findUserInfoOne() {
			let {data} = await this.$apis.findUserInfoOne({id:this.$store.state.userInfo.id});
			if(data.userInfo){
				if(data.userInfo.specialty == '专家导师' &&  this.grid.length < 14) this.grid.push({
					id: 14,
					icon: this.$mAssetsPath.kcgl,
					name: '课程管理',
					url: this.$mRoutesConfig.myClassroom
				});
			}else{
				this.$delete(this.grid,13,1)
			}
		},
        handleTreeChange(e) {
            this.hbLyValue = e
                .map(item => {
                    return item.label;
                })
                .join(',');
        },
        async dictionaryFetchDict(keyWords) {
            // const params = { keys: ['all_adept_field'] };
            // let result = await this.$apis.fetchMultipleKey(params);

            // this.fetchDict = result.data?.all_adept_field || [];

            // this.$forceUpdate();

            // setTimeout(() => {
            //     this.fetchDict = result.data?.all_adept_field || [];

            //     this.$forceUpdate();
            // }, 1000);
            
            // setTimeout(() => {
            //     this.fetchDict = result.data?.all_adept_field || [];
            
            //     this.$forceUpdate();
            // }, 2000);
        },
        handleCityChange(e) {
            const { area, city, province } = e;

            let value = '';

            if (province) {
                value = province.label;
            }

            if (city) {
                value += '-' + city.label;
            }

            if (area) {
                value += '-' + area.label;
            }

            this.hbDyValue = value;
        },
        handleShowSelect() {
            this.isSelectShow = true;
        },
        async matchCustomerServicerByType() {
            if (!this.csTypeId) {
                uni.showToast({
                    title: '请选择客服类型',
                    icon: 'none'
                });
                return;
            }
            let result = await this.$apis.matchCustomerServicerByType({
                csTypeId: this.csTypeId
            });
            if (result.code == 200) {
                uni.setStorageSync('tmpMsgId', result.data);
                // uni.setStorageSync('msgType', 999);
                uni.navigateTo({
                    url: '../customer/index'
                });
            } else {
                uni.showToast({
                    title: '暂无客服在线',
                    icon: 'none'
                });
            }
        },
        async getCustomerServiceType() {
            let result = await this.$apis.dictGroup({
                dictCode: 'customer_service_type'
            });
            this.customerServiceType = result.data;
            if (result.data.length > 0) {
                this.csTypeId = this.customerServiceType[0].id;
            }
        },
        async getMyIndex() {
            let result = await this.$apis.myIndex();
            this.my = result.data;
            this.menu[0].num = this.my.bcSum;
            this.menu[1].num = this.my.aSum;
            this.menu[2].num = this.my.fpSum;
        },
        async getfetchUserReviewed() {
            let result = await this.$apis.fetchUserReviewed();
            if (result.data != 1) {
                this.profileStatus = result.data;
                this.statusTitle = result.message;
                this.$forceUpdate();
            } else {
                this.statusTitle = '主页设置';
            }
        },
        handleClickRelease() {
            uni.switchTab({
                url: '../tabBar/release'
            });
        },
        async handleClickHb() {
            if (!this.regNumber(this.hbCountValue)) {
                this.hbCountValue = '';
                return;
            }

            if (!this.regNumber(this.hbInputValue)) {
                this.hbInputValue = '';
                return;
            }

            let data = await this.$apis.currentAccountInfo();
            if (data.code !== 200) {
                return;
            }

            if (data.data.zhcoin < +this.hbInputValue * +this.hbCountValue) {
                this.$refs.uToast.show({
                    title: '余额不足',
                    type: 'default'
                });

                return;
            }

            this.$store.commit(
                'WEBSOCKET_SEND',
                JSON.stringify({
                    type: 'sendRedPacket',
                    fromUserId: this.userInfo.id,
                    redPacketInfo: {
                        type: 1,
                        money: '' + this.hbInputValue,
                        count: '' + this.hbCountValue,
                        ruleType: '' + this.hbTypeId,
                        dy: this.hbDyValue,
                        ly: this.hbLyValue
                    }
                })
            );

            this.hbLyValue = '';
            this.hbDyValue = '';
            this.hbInputValue = '';
            this.hbCountValue = '';
        },
        regNumber(number) {
            if (!number) {
                this.$refs.uToast.show({
                    title: '内容不能为空',
                    type: 'default'
                });

                return false;
            }

            if (!/^[0-9]*$/.test(number)) {
                this.$refs.uToast.show({
                    title: '请输入整数',
                    type: 'default'
                });

                return false;
            }

            return true;
        },
        handleClickMsg() {
            if (this.userName == '登录/注册') {
                uni.navigateTo({
                    url: '../login/login'
                });
            } else {
                uni.navigateTo({
                    url: '../message/index'
                });
            }
        },
        handleClickMemu(e) {
            var _this = this;
            let url = _this.menu[e].url;
            console.log('url', url);
            if (e === 3) {
                this.$refs.uToast.show({
                    title: '正在开发，敬请期待',
                    type: 'success'
                });
                return;
            }
            _this.$mRouter.push({
                route: url
            });
        },
        msg() {
            this.$mRouter.push({
                route: this.$mRoutesConfig.login
            });
        },
        profile() {
            if (this.$store.state.userInfo.identityType != undefined) {
                if (this.$store.state.userInfo.identityType == 1) {
                    uni.navigateTo({
                        url: '../user/myCompanyPage'
                    });
                } else {
                    uni.navigateTo({
                        url: '../user/myHomePage'
                    });
                }
            } else {
                uni.navigateTo({
                    url: '../login/login'
                });
            }
        },
        async toLogin() {
            if (this.userName == '登录/注册') {
                uni.navigateTo({
                    url: '../login/login'
                });
            } else {
                let data = await this.$apis.switchUser();
                if (data.code == 200) {
                    // 前端自动登录
                    this.$store.commit('SET_USERINFO', data.data);
                    uni.setStorageSync('userInfo', data.data);
                    console.log(uni.getStorageSync('userInfo'));
                    uni.showToast({
                        title: '切换成功',
                        icon: 'none'
                    });
                    this.$store.commit(
                        'WEBSOCKET_SEND',
                        JSON.stringify({
                            type: 'login',
                            msg: { userId: data.data.id, name: data.data.name }
                        })
                    ); //发送当前聊天窗口信息

                    var that = this;
                    setTimeout(() => {
                        that.$mRouter.switchTab({
                            route: that.$mRoutesConfig.index
                        });
                    }, 1000);
                } else {
                    uni.showToast({
                        title: data.message,
                        icon: 'none'
                    });
                    this.submitBtnDis = false;
                    return;
                }
            }
            // uni.navigateTo({
            // 	url:'../login/login'
            // })
        },
        async handleClickGrid(e) {
            console.log(this.$store.state.userInfo);
            if (uni.getStorageSync('userInfo') === '') {
                this.$refs.uToast.show({
                    title: '请先登录',
                    type: 'default'
                });
                return;
            }
            console.log(e);
            var _this = this;
            //小区是否开放权限
            let index = e.index - 1;
            if (index === 1) {
                this.modalShow = true;
                this.getCustomerServiceType();
                return;
            }

            if (index === 14) {
                this.findUserInfoOne();
            }
            if (index === 12) {
                this.$refs.uToast.show({
                    title: '正在开发，敬请期待',
                    type: 'success'
                });
                return;
            }
            if (index === 4) {
                let result = await this.$apis.checkIsJoin();
                if (result.data.result) {
                    if (result.data.statusTitle == '审核通过') {
                    } else {
                        uni.showToast({
                            title: '您的加入伙伴正在申请审核中！',
                            icon: 'none'
                        });
                        return;
                    }
                } else {
                    uni.showToast({
                        title: '请先申请加入伙伴！',
                        icon: 'none'
                    });
                    return;
                }
            }
            if (index == 9 && this.$store.state.userInfo.identityType != 1) {
                this.$refs.uToast.show({
                    title: '只有企业用户可以访问',
                    type: 'none'
                });
                return;
            }
            console.log(index);
            let url = _this.grid[index].url;
            console.log(url);
            _this.$mRouter.push({
                route: url
            });
        }
    }
};
</script>

<style scoped lang="scss">
page,
.container {
    background-color: #f4f4f4;
    padding-bottom: 30rpx;
}
.status_bar {
    height: var(--status-bar-height);
    width: 100%;
}

.top_view {
    height: var(--status-bar-height);
    width: 100%;
    position: fixed;
    top: 0;
    z-index: 999;
}
.top {
    display: flex;
    justify-content: flex-end;
    padding: 20rpx 37rpx 4rpx 0;
}

.top image {
    width: 42rpx;
    height: 40rpx;
}
.u-radio-group {
    padding: 30rpx;
}
.header {
    width: 750rpx;
    height: 400rpx;
    background-size: 100% auto;
    background-position: 0 bottom;

    .user {
        padding-top: 4rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .avatar {
            width: 110rpx;
            height: 127rpx;
            margin: 0 34rpx 0 28rpx;
            border-radius: 55rpx;
        }

        .name {
            font-size: 40rpx;
            font-weight: 500;
            color: #ffffff;
        }
    }

    .total {
        padding-top: 25rpx;
        /* #ifdef H5 */
        padding-top: 54rpx;
        /* #endif */
        display: flex;
        justify-content: space-around;
        font-size: 22rpx;

        view {
            display: flex;
            flex-direction: column;
            text-align: center;
            color: #fff;

            text {
                padding-bottom: 10rpx;
                /* #ifdef H5 */
                padding-bottom: 22rpx;
                /* #endif */
                font-weight: 700;
                font-size: 44rpx;
            }
        }
    }

    .qhsf {
        width: 208rpx;
        height: 69rpx;
    }
}

.my-home {
    margin: 30rpx auto;
    width: 690rpx;
    background-color: #fff;
    border-radius: 10rpx;

    .star {
        background: #ffe2cf;
        padding: 25rpx 26rpx;
        border-radius: 10rpx 10rpx 0 0;
        color: #ff3300;
    }
}

.title {
    padding: 30rpx;

    text {
        color: #0d1d36;
        font-weight: 700;
    }

    navigator {
        color: #ab61ff;
    }

    .more {
        width: 14rpx;
        height: 24rpx;
        margin-left: 19rpx;
    }
}

.f-logo {
    margin: 29rpx 27rpx 24rpx 42rpx;
    width: 102rpx;
    height: 118rpx;
    image {
        width: 102rpx;
        height: 118rpx;
    }
}

.add {
    .btn {
        width: 160rpx;
        height: 62rpx;
        line-height: 62rpx;
        border: 2rpx solid #ab61ff;
        border-radius: 28rpx;
        text-align: center;
        color: #ab61ff;
        font-size: 24rpx;
    }
}

.menus {
    background-color: #fff;
    width: 690rpx;
    margin: 0 auto;
    border-radius: 10rpx;
}
.vip,
.up-vip {
    width: 44rpx;
    height: 22rpx;
    padding: 0 10rpx;
}

.slot-content-select {
    line-height: 32px;
    margin-right: 20px;
}
.slot-content-input {
    padding: 0 18px;
    display: flex;
    align-items: center;

    text {
        width: 38px;
        line-height: 32px;
        margin-right: 20px;
    }

    .m-input-view {
        width: 235px;
    }
}
</style>
